<!-- 职位管理新增组件 -->
<template>
  <a-drawer
    :width="600"
    v-model:visible="modalVisible"
    @ok="handleOk"
    @cancel="handleCancel"
    unmount-on-close
  >
    <template #title> 新增职位 </template>
    <div>
      <a-form :model="formData" ref="refForm" :rules="rules" auto-label-width>
        <a-form-item label="公司：" field="companyId">
          <a-select
            placeholder="请选择"
            v-model="formData.companyId"
            @change="companySelect"
          >
            <a-option
              v-for="item in companyList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属部门：" field="organizationId">
          <a-tree-select
            :fieldNames="{
              key: 'id',
              title: 'name' // 部门的code
            }"
            :data="deptList"
            v-model="formData.organizationId"
            placeholder="请选择"
          ></a-tree-select>
          <!-- <a-select v-model="formData.organizationId">
            <a-option
              v-for="(item, index) in deptList"
              :key="index"
              :value="item.value"
            >
              {{ item.label }}
            </a-option>
          </a-select> -->
        </a-form-item>
        <a-form-item label="职位名称：" field="name">
          <template #extra>
            <div>选择完公司和部门才能填写职位名称</div>
          </template>
          <a-input
            placeholder="请输入"
            v-model="formData.name"
            :disabled="!formData.organizationId"
          ></a-input>
        </a-form-item>
        <a-form-item label="职位编码：" field="positionCode">
          <a-input
            placeholder="系统自动生成"
            v-model="formData.positionCode"
            disabled
          ></a-input>
        </a-form-item>
        <a-form-item label="上级职位：" field="upPosition">
          <a-tree-select
            :fieldNames="{
              key: 'id',
              title: 'name' // 部门的code
            }"
            :data="positionList"
            v-model="formData.upPosition"
            placeholder="请选择"
            dropdown-class-name="tree-drop-down-indent-size"
          >
            <template #tree-slot-switcher-icon="node, { isLeaf }">
              <IconDown v-if="!isLeaf" />
              <IconStar v-if="isLeaf" />
            </template>
            <template #tree-slot-title="nodeData">
              <span
                :style="{
                  paddingLeft:
                    nodeData.level > 2
                      ? '32px'
                      : (nodeData.level - 1) * 16 + 'px'
                }"
              >
                {{ nodeData.name }}
              </span>
            </template>
          </a-tree-select>
        </a-form-item>
        <a-form-item label="编制人数：" field="headcount">
          <a-input-number
            placeholder="请输入"
            v-model="formData.headcount"
            hide-button
          ></a-input-number>
        </a-form-item>
        <a-form-item label="关联职务：" field="relatedId">
          <a-select v-model="formData.relatedId" placeholder="请选择">
            <a-option v-for="item in jobList" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="关联标准职位：" field="">
          <template #extra>
            <div>如果同时选择标准职位和职位说明书则以职位说明书模板为准</div>
          </template>
          <a-select
            v-model="formData.standJobId"
            placeholder="请选择"
            @change="standJobSelect"
          >
            <a-option
              v-for="item in positionStandList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="职位类别：" field="positionTypeId">
          <a-tree-select
            v-model="formData.positionTypeId"
            :fieldNames="{
              key: 'id',
              title: 'name'
            }"
            :data="positionTypeList"
            placeholder="请选择"
            :allow-search="true"
            allow-clear
            :filter-tree-node="filterPositionType"
            @change="positionTypeChange(formData.positionTypeId)"
            @clear="clearType"
            ref="positionTypeRef"
          ></a-tree-select>
        </a-form-item>
        <!-- <a-form-item label="职位序列：" field="">
          <a-select v-model="formData.positionSequenceId" placeholder="请选择">
            <a-option></a-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="选择职位说明书模板：" field="templateId">
          <template #label>
            <span
              >选择职位说明书模板：
              <a-tooltip
                content="注意：如果先选择了职位类别，则优先使用对应职位类别里面的模板。否则优先使用职位说明书的模板！"
              >
                <icon-exclamation-circle-fill style="color: #165dff" />
              </a-tooltip>
            </span>
          </template>
          <a-select
            allow-search
            allow-clear
            v-model="formData.templateId"
            placeholder="请选择"
          >
            <a-option
              v-for="item in templateList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="选择人员模板：" field="personnelTemplateId">
          <a-select
            allow-search
            allow-clear
            v-model="formData.personnelTemplateId"
            placeholder="请选择"
          >
            <a-option
              v-for="item in personTemplateList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="职位层级：" field="positionLevelId">
          <a-select
            v-model="formData.positionLevelId"
            placeholder="请选择"
            @change="handlePositionLevel"
          >
            <a-option
              v-for="item in positionLevelList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="职级范围：" field="positionRange">
          <!-- <a-select v-model="formData.positionRange" placeholder="请选择">
            <a-option></a-option>
          </a-select> -->
          <a-select
            :disabled="!formData.positionLevelId"
            v-model="formData.positionRange"
            :popup-visible="false"
            @click="openModal"
            placeholder="请选择"
          >
          </a-select>
        </a-form-item>
        <a-form-item label="是否特殊工种：" field="">
          <a-radio-group v-model="formData.isSpecial">
            <a-radio value="是">是</a-radio>
            <a-radio value="否">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="是否关键职位：" field="">
          <a-radio-group v-model="formData.isKey">
            <a-radio value="是">是</a-radio>
            <a-radio value="否">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="职位使命：" field="">
          <a-textarea
            allowClear
            v-model="formData.remark"
            :maxLength="300"
            :autoSize="{
              minRows: 5
            }"
            placeholder="请输入"
            showWordLimit
          ></a-textarea>
        </a-form-item>
        <a-form-item label="是否设为标准职位：" field="">
          <a-radio-group v-model="formData.isStand">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="2">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="是否启用该职位：" field="enable">
          <a-radio-group v-model="formData.enable">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="2">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>

  <a-modal
    v-model:visible="modalShow"
    @ok="modelOK"
    @cancel="modalShow = false"
  >
    <template #title> 选择职级 </template>
    <div class="radio">
      <a-radio-group v-model="radioShow" style="margin-bottom: 20px">
        <a-radio value="A">单个职级 </a-radio>
        <a-radio value="B">职级范围 </a-radio>
      </a-radio-group>
      <div class="son-radio" v-show="radioShow === 'A'">
        职级({{ positionRangeData[0]?.levelDown }}~{{
          positionRangeData[0]?.levelUp
        }})：
        <a-input-number
          v-model="positionRangeNum.num"
          :min="positionRangeData[0]?.levelDown"
          :max="positionRangeData[0]?.levelUp"
          style="width: 150px"
        />
      </div>
      <div class="son-radio" v-show="radioShow === 'B'">
        <span>
          职级范围({{ positionRangeData[0]?.levelDown }}~{{
            positionRangeData[0]?.levelUp
          }})：</span
        >
        <a-input-number
          v-model="positionRangeNum.min"
          :min="positionRangeData[0]?.levelDown"
          :max="positionRangeData[0]?.levelUp"
          style="width: 150px"
        />
        <span style="margin: 0 10px">—</span>
        <a-input-number
          v-model="positionRangeNum.max"
          :min="positionRangeNum.min"
          :max="positionRangeData[0]?.levelUp"
          style="width: 150px"
        />
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { dataTreeFilter } from '@/utils/utils';
import {
  GetPositionTypeList,
  GetPositionLevelList
} from '@/apis/management/organization/baseSetting';
import { GetPosition } from '@/apis/management/organization/positionManagement';
import {
  GetPositionTemplate,
  GetPositionTypeCodeById
} from '@/apis/management/organization/baseSetting/PositionSystem';
import { validateRules } from '@/utils/common';
import { GetlistData } from '@/apis/management/personnel/baseSetting/TransactionSetting';
import {
  GetJobList,
  CheckPositionList,
  GetPositionStandard,
  GetPositionStandardDetail
} from '@/apis/management/organization/positionManagement';
import { GetHumanTemplateList } from '@/apis/management/human/baseSetting/humanSetting';
import { cloneDeep } from 'lodash';

const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    list?: any; // 传进来的数据
  }>(),
  {
    visible: false
  }
);

const emit = defineEmits(['update:visible', 'positionAddEmit']);

const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible: boolean) {
    emit('update:visible', visible);
  }
});

// 职位名称查重
const validateName = async (val: any, cb: any, type: number) => {
  try {
    if (!val) return;
    let data = {
      name: val,
      id: formData.value.organizationId
    };
    const res = await validateRules(CheckPositionList, data);
    if (res.code) {
      cb(`${res.msg}`);
    } else return;
  } catch (error: unknown) {
    console.log(error);
  }
};

const rules = {
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ],
  positionCode: [],
  companyId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  organizationId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  // headcount: [
  //   {
  //     required: true,
  //     message: '请输入'
  //   }
  // ],
  // relatedId: [
  //   {
  //     required: true,
  //     message: '请选择'
  //   }
  // ],
  positionTypeId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  templateId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  personnelTemplateId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  positionLevelId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  positionRange: [
    {
      required: true,
      message: '请选择'
    }
  ],
  enable: [
    {
      required: true,
      message: '请选择'
    }
  ]
};

// 职位对象类型定义
interface TformData {
  // 职位名称
  name: string;
  // 职位编码
  positionCode: string;
  // 职位类别编码
  positionTypeCode: string;
  // 公司ID
  companyId: number | undefined;
  // 所属部门ID
  organizationId: number | undefined;
  // 编制人数
  headcount: number | undefined;
  // 关联职务ID
  relatedId: number | undefined;
  // 关联标准职位ID
  standJobId: number | undefined;
  // 职位类别ID
  positionTypeId: number | undefined;
  // 职位类别名称
  positionType: string;
  // 上级职位id
  upPosition: number | undefined;
  // 职位序列ID
  positionSequenceId: number;
  // 职位模板ID
  templateId: number | undefined;
  // 人员模板ID
  personnelTemplateId: number | undefined;
  // 职位层级ID
  positionLevelId: number | undefined;
  // 职位范围
  positionRange: string | undefined;
  // 是否特殊工种，是或否
  isSpecial: '是' | '否';
  // 是否关键职位，是或否
  isKey: '是' | '否';
  // 职位使命描述
  remark: string;
  // 是否标准职位，1表示是，2表示否
  isStand: 1 | 2;
  // 是否启用该职位，1表示是，2表示否
  enable: 1 | 2;
  // 控制项数组，具体内容根据实际需求定义
  controlItems: any[];
}

let formData = ref<TformData>({
  name: '', // 职位名称
  positionCode: '', // 职位编码
  positionTypeCode: '', // 职位类别编码
  companyId: undefined, // 公司id
  organizationId: undefined, // 所属部门
  upPosition: undefined, // 上级职位id
  headcount: undefined, // 编制人数
  relatedId: undefined, // 关联职务
  standJobId: undefined, // 关联标准职位
  positionTypeId: undefined, // 职位类别
  positionType: '', // 职位类别名称
  positionSequenceId: 1, // 职位序列
  templateId: undefined, // 模板id
  personnelTemplateId: undefined, // 人员模板id
  positionLevelId: undefined, // 职位层级
  positionRange: undefined, // 职位范围
  isSpecial: '否', // 是否特殊工种
  isKey: '否', // 是否关键职位
  remark: '', // 职位使命
  isStand: 2, // 是否标准职位 1是 2否,
  enable: 1, // 是否启用该职位 1是 2否
  controlItems: []
});

const initData = cloneDeep(formData.value); // 储存初始数据

let organizationDeptList = ref<any>([]); // 储存部门类别
let positionTypeList = ref<any>([]); // 储存职位类别
let positionLevelList = ref<any>([]); // 储存职位层级
let companyList = ref<any>([]); // 储存公司类型的数据
let positionStandList = ref<any>([]); // 储存标准职位库数据
let personTemplateList = ref<any>([]); // 储存人员模板列表数据
let positionList = ref(); // 储存职位列表数据
let jobList = ref<any>([]); // 储存职务数据

const getData = async () => {
  try {
    const [
      // 获取职位类型
      positionTypeListRes,
      // 获取职位层级
      positionLevelListRes,
      // 获取职务管理数据
      jobListRes,
      // 获取公司
      companyListRes,
      // 获取标准职位列表
      positionStandListRes,
      // 获取人员模板列表
      humanTemplateListRes,
      // 获取职位列表
      positionListRes,
      // 获取职位说明书
      templateListRes
    ] = await Promise.all([
      // GetOrganizationList({}),
      GetPositionTypeList(),
      GetPositionLevelList({ pageNumber: 0, pageSize: -1 }),
      GetJobList({ pageNumber: 0, pageSize: -1 }),
      GetlistData({ type: 1 }),
      GetPositionStandard({ pageNumber: 0, pageSize: -1 }),
      GetHumanTemplateList({ pageNumber: 0, pageSize: -1 }),
      GetPosition({
        pageNumber: 0,
        pageSize: -1
      }),
      GetPositionTemplate({
        pageNumber: 0,
        pageSize: -1,
        ownerType: 4
      })
    ]);

    positionTypeList.value = dealTreeData(
      positionTypeListRes.positionCategoryList
    ).filter((item: any) => item.isEnable === 1); // 启用状态下的职位类型才能选择

    positionLevelList.value = positionLevelListRes.content;
    jobList.value = jobListRes.content.filter(
      (item: any) => item.postStatus === 1
    ); // 启用状态才能选择
    companyList.value = companyListRes.filter((item: any) => item.enable === 1); // 启用状态下的组织才能被选择
    // 启用状态才能选择
    positionStandList.value = positionStandListRes.content.filter(
      (item: any) => item.enable === 1
    );
    personTemplateList.value = humanTemplateListRes.content.filter(
      (item: any) => item.enable === 1
    );
    positionList.value = dataTreeFilter(positionListRes.content, 'enable');

    templateList.value = templateListRes.content.filter(
      (el: any) => el.enable === 1
    );
    console.log(
      '🚀 ~ file: index.vue:544 ~ getData ~ positionList.value:',
      positionList.value
    );
  } catch (error) {
    console.log(error);
  }
};

watch(
  () => modalVisible.value,
  (newVal: boolean, oldVal: boolean) => {
    if (newVal) getData();
  }
);

let deptList = ref([]); // 储存当前选择的公司下的部门
const companySelect = async (id: number) => {
  deptList.value = [];
  formData.value.organizationId = undefined;
  deptList.value = await GetlistData({
    type: 2,
    id
  });
  deptList.value = deptList.value.filter((item: any) => item.enable === 1);
};

// 重新组合树数据(根据需要来重组树结构中的属性字段，用来新增判断是否为叶子节点信息)
const dealTreeData = (treeData: any) => {
  const data = treeData.map((item: any) => ({
    ...item,
    // ...controldataTreeFilter(item.controlData),
    // 新增叶子节点字段
    isLeaf: item.children ? false : true,
    // 新增是否能被选中字段，默认只能选叶子
    selectable: item.children ? false : true,
    // 如果children为空数组，则置为null
    children:
      item.children && item.children.length ? dealTreeData(item.children) : null
  }));
  return data;
};

// 模糊搜索职位类型
const filterPositionType = (searchValue: string, nodeData: any) => {
  return nodeData.name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1;
};

const templateList = ref([]); // 储存当前模板列表数据

let positionTypeRef = ref();

// 选择职位类型事件
const positionTypeChange = async (ownerId: number | undefined) => {
  try {
    if (!formData.value.templateId) {
      nextTick(async () => {
        console.dir(positionTypeRef.value);

        formData.value.positionType =
          positionTypeRef.value.selectedValue[0].label;
        formData.value.templateId = undefined;
        formData.value.positionTypeCode = await fetchPositionCode(
          ownerId as number
        );
        templateList.value = await fetchPositionTemplate(ownerId as number, 2);
        formData.value.templateId = findDefaultTemplateId();
      });
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 清除职位类别
const clearType = async () => {
  try {
    formData.value.templateId = undefined;
    templateList.value = await fetchPositionTemplate(null, 4);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 获取职位模板
const fetchPositionTemplate = async (
  ownerId: number | null,
  ownerType: 2 | 4
) => {
  const { content } = await GetPositionTemplate({
    pageNumber: 0,
    pageSize: -1,
    ownerId,
    ownerType
  });
  return content.filter((item: any) => item.enable === 1);
};

// 获取默认模板
const findDefaultTemplateId = () => {
  const defaultTemplate = templateList.value.find(
    (item: any) => item.isShowDefault === 1
  );
  return defaultTemplate?.id;
};

// 根据职位类别id查找职位类别编码
const fetchPositionCode = async (id: number) => {
  return await GetPositionTypeCodeById({ id });
};

// 选择职位层级
const handlePositionLevel = () => {
  // 每次选择其他的层级清空范围的数据
  formData.value.positionRange = undefined;
};

// 选择标准职位
const standJobSelect = async (id: number) => {
  try {
    const res = await GetPositionStandardDetail({
      id
    });

    const { content } = await GetPositionTemplate({
      // id: ID,
      pageNumber: 0,
      pageSize: -1,
      ownerId: res.positionTypeId,
      ownerType: 2
    });
    console.log(content);

    templateList.value.push(content.find((item: any) => item.enable === 1));

    formData.value.positionTypeId = res.positionTypeId;
    formData.value.templateId = res.templateId;
    formData.value.name = res.name;
    formData.value.positionType = res.positionType;
    formData.value.positionLevelId = res.positionLevelId;
    formData.value.positionRange = res.positionRange;
    formData.value.isSpecial = res.isSpecial;
    formData.value.isKey = res.isKey;
    formData.value.remark = res.remark;

    console.log(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

let modalShow = ref(false);
const radioShow = ref('A');
const positionRangeData = ref<any>([]); // 储存职位范围数据
// 存储职位范围弹窗数据
const positionRangeNum = reactive({
  num: 0,
  min: 0,
  max: 0
});

// 打开职级范围的弹出框
const openModal = () => {
  if (formData.value.positionLevelId) {
    console.log(positionRangeData);

    modalShow.value = true;
    positionRangeNum.min = positionRangeData[0].levelDown;
    positionRangeNum.max = positionRangeData[0].levelUp;
    positionRangeNum.num = positionRangeData[0].levelDown;
  }
};
const modelOK = () => {
  // modalShow.value = false;
  if (positionRangeNum.num) {
    formData.value.positionRange = `${positionRangeNum.num}`;
  } else {
    formData.value.positionRange = `${positionRangeNum.min}~${positionRangeNum.max}`;
  }
};
watch(
  () => formData.value.positionLevelId,
  () => {
    positionRangeData.value = positionLevelList.value.filter(
      (ele: any) => ele.id === formData.value.positionLevelId
    );
    console.log(positionRangeData.value, positionLevelList.value);
  }
);
watch(
  () => radioShow.value,
  () => {
    if (radioShow.value === 'A') {
      positionRangeNum.min = 0;
      positionRangeNum.max = 0;
    } else {
      positionRangeNum.num = 0;
    }
  }
);

let refForm = ref(); // 储存表单的ref
// 保存
const handleOk = async () => {
  if (await refForm.value.validate()) {
    emit('update:visible', true);
    return;
  }
  emit('positionAddEmit', formData.value);
  formData.value = cloneDeep(initData);
  emit('update:visible', false);
};

// 取消
const handleCancel = () => {
  emit('update:visible', false);
  formData.value = cloneDeep(initData);
};
</script>

<style scoped lang="less"></style>
